#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Licensed Materials - Property of tenxcloud.com
# (C) Copyright 2020 TenxCloud. All Rights Reserved.
# 2020-05-31 @author lizhen

from flask import Blueprint, jsonify, send_file, abort, request, current_app
from flask_accept import accept_fallback
from functools import wraps

from data_set_api.model import db, File, DataSet
from data_set_api.utils import save_file

import os

blueprint = Blueprint('file', __name__, url_prefix="/datasets/<string:data_set_id>/images")


def ensure_file(api):
    @wraps(api)
    def find_file(data_set_id, file_id):
        file = File.query.filter_by(data_set_id=data_set_id, id=file_id).first()
        if file is None:
            abort(404, "image not found")
        return api(data_set_id, file_id, file)

    return find_file


@blueprint.route('/<string:file_id>', methods=['GET'], strict_slashes=False)
@accept_fallback
@ensure_file
def get(data_set_id, file_id, file):
    os.path.join(current_app.config['FILE_FOLDER_ROOT'], data_set_id, file.filename)
    return send_file(
        os.path.join(current_app.config['FILE_FOLDER_ROOT'],
                     data_set_id, file.mask),
        as_attachment=True,
        attachment_filename=file.filename)


@get.support('application/json')
@ensure_file
def get_info(data_set_id, file_id, file):
    return jsonify(file)


@blueprint.route('/<string:file_id>', methods=['DELETE'], strict_slashes=False)
@ensure_file
def delete(data_set_id, file_id, file):
    db.session.delete(file)

    full_path = os.path.join(
        current_app.config['FILE_FOLDER_ROOT'], data_set_id, file.filename)
    if os.path.exists(full_path):
        os.remove(full_path)

    db.session.commit()

    return "", 204


@blueprint.route('', methods=['PUT'], strict_slashes=False)
def update(data_set_id):
    data_set = DataSet.query.get(data_set_id)
    if data_set is None:
        abort(404, "data set not found")

    data_set_folder = os.path.join(
        current_app.config['FILE_FOLDER_ROOT'], data_set_id)
    files = [File(**save_file(file, data_set_id, data_set_folder))
             for file in request.files.getlist("files")]

    data_set.files.extend(files)

    db.session.commit()

    return jsonify(files)
